package com.ruoyi.gateway.config;

import com.ruoyi.common.core.exception.CaptchaException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.gateway.handler.ValidateCodeHandler;
import com.ruoyi.gateway.handler.ValidateCodeHandlerTest;
import com.ruoyi.gateway.service.ValidateCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.io.IOException;

import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.path;

/**
 * 路由配置信息
 *  WebFlux
 * @author ruoyi
 */
@Configuration
public class RouterFunctionConfiguration {
    @Autowired
    private ValidateCodeHandler validateCodeHandler;

    @Autowired
    private ValidateCodeService validateCodeService;

    @SuppressWarnings("rawtypes")
    @Bean
    public RouterFunction routerFunction() {
        return RouterFunctions.route(
                RequestPredicates.GET("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
                validateCodeHandler);
//        return RouterFunctions.route(
//                GET("/code").and(RequestPredicates.accept(MediaType.TEXT_PLAIN)),
//                s -> {
//                    AjaxResult ajax;
//                    try {
//                        ajax = validateCodeService.createCaptcha();
//                    } catch (CaptchaException | IOException e) {
//                        return Mono.error(e);
//                    }
//                    return ServerResponse.status(HttpStatus.OK).body(BodyInserters.fromValue(ajax));
//                });

    }

    @Bean
    public RouterFunction<ServerResponse> getModelBuildingRouters(ValidateCodeHandlerTest modelBuildingHandler) {
        return RouterFunctions.nest(path("/model/building"),
                RouterFunctions.route(GET("/{entId}/stations"), modelBuildingHandler::handle)
                        .andRoute(GET("/{stationId}/device-types"), modelBuildingHandler::handle)
        );
    }

}
